package com.hiwan.unions.util;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.hiwan.unions.R;
import com.hiwan.unions.activity.loginRegister.LoginUserActivity;
import com.hiwan.unions.activity.system.FeedbackActivity;
import com.hiwan.unions.application.ConstantsValues;
import com.hiwan.unions.application.exception.ApiException;
import com.hiwan.unions.application.request.ConstsNet;
import com.hiwan.unions.view.ProgressWebView;
import com.yanzhenjie.nohttp.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import static com.hiwan.unions.util.CommonUtils.getString;

/**
 * Created by llg on 2017/3/30.
 */
public class CheckUtils extends Utils {
    //身份证验证
    public static String checkReal(EditText real) throws ApiException {
        if (isEmpty(real)) {
            throw new ApiException(getString(R.string.enter_real_error));
        }
        if (!RealCardCheckUtils.isValidatedAllIdcard(real.getText().toString())) {
            throw new ApiException(getString(R.string.enter_real_error2));
        }
        return StringFilter(real.getText().toString());
    }

    //身份证验证
    public static String checkReal(String realToString, String realToDate) throws ApiException {
        if (isEmpty(realToString)) {
            throw new ApiException(getString(R.string.enter_real_error));
        }
        if (isRealCard(realToDate)) {
            throw new ApiException(getString(R.string.enter_real_error2));
        }
        if (isEmpty(realToString)) {
            throw new ApiException(getString(R.string.enter_real_error));
        }
        Logger.i("data" + realToString.substring(6, 14));
        if (realToString.substring(6, 14).equals(realToDate)) {
            throw new ApiException(getString(R.string.enter_real_error2));
        }
        return realToString;
    }

    public static boolean isRealCard(String s_aStr) {
        String reg18 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
        String reg15 = "^[1-9]\\\\d{7}((0\\\\d)|(1[0-2]))(([0|1|2]\\\\d)|3[0-1])\\\\d{3}$";
        if (s_aStr.matches(reg15) || s_aStr.matches(reg18)) {
            return true;
        }
        return false;
    }

    //手机号码验证
    public static String checkMobile(EditText mobile) throws ApiException {
        if (isEmpty(mobile)) {
            throw new ApiException(getString(R.string.please_enter_mobile));
        }
        if (!isMobileNO(mobile)) {
            throw new ApiException(getString(R.string.enter_mobile_error));
        }
        return StringFilter(mobile.getText().toString());
    }

    //重置手机号码验证
    public static String checkUpdateMobile(EditText mobile, String phone) throws ApiException {
        if (isEmpty(mobile)) {
            throw new ApiException(getString(R.string.enter_updatePhone_error2));
        }
        if (!isMobileNO(mobile)) {
            throw new ApiException(getString(R.string.enter_mobile_error));
        }
        if (phone.equals(mobile.getText().toString())) {
            throw new ApiException(getString(R.string.enter_updatePhone_error3));
        }

        return StringFilter(mobile.getText().toString());
    }

    //注册密码验证
    public static String checkRegisterPaaword(EditText password) throws ApiException {
        if (isEmpty(password)) {
            throw new ApiException(getString(R.string.enter_registerpassword_error));
        }
        checkLoginLen(password);
        return Base64Util.encode(password.getText().toString().getBytes());
    }

    //字符串校验
    public static String check(EditText userName, String title) throws ApiException {
        if (isEmpty(userName)) {
            throw new ApiException(title);
        }
        return userName.getText().toString();
    }

    //字符串校验
    public static String check(String userName, String code2, String code) {
        if (isEmpty(userName) || code2.equals(code)) {
            return "";
        }
        return userName;
    }

    //字符串校验
    public static boolean checkBoolean(TextView editText, String title) {
        return editText.getText().toString().equals(title);
    }

    //字符串校验
    public static boolean checkBoolean(EditText editText, String title) {
        return editText.getText().toString().equals(title);
    }

    public static String check(TextView userName, String title) throws ApiException {
        if (isEmpty(userName)) {
            throw new ApiException(title);
        }
        return userName.getText().toString();
    }

    //修改密码验证
    public static String checkUpdatePaaword(EditText password) throws ApiException {
        if (isEmpty(password)) {
            throw new ApiException(getString(R.string.enter_updatepassword_error));
        }
        return Base64Util.encode(password.getText().toString().getBytes());
    }

    //修改密码验证2
    public static String checkUpdatePaaword2(EditText password) throws ApiException {
        if (isEmpty(password)) {
            throw new ApiException(getString(R.string.enter_updatePhonePassword_error2));
        }
        checkLoginLen(password);
        return Base64Util.encode(password.getText().toString().getBytes());
    }

    //登录密码验证
    public static void checkLoginLen(EditText password) throws ApiException {
        if (password.length() < 8) {
            throw new ApiException(getString(R.string.enter_loginPassword_error_l));
        }
    }

    //登录密码验证
    public static String checkLoginPaaword(EditText password) throws ApiException {
        if (isEmpty(password)) {
            throw new ApiException(getString(R.string.enter_loginPassword_error));
        }
        return Base64Util.encode(password.getText().toString().getBytes());
    }


    //登录密码验证
    public static String checkUpdatePhonePaaword(EditText password) throws ApiException {
        if (isEmpty(password)) {
            throw new ApiException(getString(R.string.enter_updatePhone_error));
        }
        return Base64Util.encode(password.getText().toString().getBytes());
    }

    //地址替换
    public static String checkCity(String city) throws ApiException {
        if (containsString(city, "阿坝")) {
            throw new ApiException("阿坝");
        }
        if (containsString(city, "甘孜")) {
            throw new ApiException("甘孜");
        }
        if (containsString(city, "凉山")) {
            throw new ApiException("凉山");
        }
        return city;
    }


    public static void checkLogin(ProgressWebView webView, Context context, String type, String title, String url) {
        if (type.equals("DifficultyForm") || type.equals("LegalAdviceForm")) {
            FeedbackActivity.startPreview(context, title);
        } else if (type.equals("WEB")) {
            Utils.callHelpDeilsActivity(url, context, "");
        } else {
            webView.quickCallJs(type);
        }
    }

    //验证码验证
    public static String checkYzm(EditText yzm) throws ApiException {
        if (isEmpty(yzm)) {
            throw new ApiException(getString(R.string.enter_yzm_error));
        }
        return yzm.getText().toString();
    }


    //用户名验证
    public static String checkName(SharedPreferences userInfo) throws ApiException {
        if (isEmpty(userInfo.getString(ConstantsValues.name, ""))) {
            throw new ApiException(retunPhone(userInfo));
        }
        return userInfo.getString(ConstantsValues.name, "");
    }

    //用户名验证
    public static String checkName(SharedPreferences userInfo, String name) throws ApiException {
        if (isEmpty(name)) {
            throw new ApiException(retunPhone(userInfo));
        }
        return name;
    }


    //手机号保密
    public static String retunPhone(SharedPreferences userInfo) throws ApiException {
        StringBuilder Phone = new StringBuilder(userInfo.getString(ConstantsValues.phone, ""));
        if (Phone.length() > 0) {
            return Phone.replace(3, 7, "****").toString();
        } else {
            return "";
        }
    }


    //判断用户是否登录
    public static boolean userInfo(SharedPreferences userInfo) {
        if (userInfo.getBoolean(ConstantsValues.IS_HASLOGIN, false)) {
            return true;
        }
        return false;
    }

    //判断用户是否登录
    public static boolean userInfo(Context context) {
        SharedPreferences userInfo = context.getSharedPreferences(ConstantsValues.INIT_USER_INFO, Context.MODE_PRIVATE);
        if (userInfo.getBoolean(ConstantsValues.IS_HASLOGIN, false)) {
            return true;
        } else {
            LoginUserActivity.startPreview(context);
            return false;
        }
    }

    /**
     * 判断字符串是否包含一些字符 contains
     */
    public static boolean containsString(String src, String dest) {
        boolean flag = false;
        if (isEmpty(src))
            return flag;
        if (isEmpty(dest))
            return flag;
        if (src.contains(dest)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(EditText editText) {
        String mobiles = StringFilter(editText.getText().toString());
        String telRegex = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、4、5、7、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    public static boolean isEmpty(String s) {
        return s == null || s.length() == 0;
    }

    public static String isEmpty(String s, String s2) {
        if (s == null || s.length() == 0) {
            return s2;
        } else {
            return s;
        }
    }

    //地址替换
    public static String checkAddressUrl(String city) {
        if (isEmpty(city))
            return city;
        if (CheckUtils.containsString(city, "http"))
            return city;
        if (city.substring(0, 1).equals("/")) {
            return ConstsNet.LILINTONG_URLWEB + city;
        } else {
            return ConstsNet.LILINTONG_URLWEB + city;
        }
    }


    public static boolean isEmpty(EditText s) {
        return s.length() == 0;
    }

    public static boolean isEmpty(TextView s) {
        return s.length() == 0;
    }

    public static boolean isEmpty(String s, int i) {
        return s == null || s.length() != i;
    }


    /**
     * 微信程序判断
     */
    public static boolean isWeixinAvilible(Context context, String time) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(time)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 图片文件大小  判断是否超出10m
     */
    public static boolean daxiao(String s1) {
        boolean b = false;
        try {
            int fileLen = 0;
            File dF = new File(s1);
            FileInputStream fis;
            fis = new FileInputStream(dF);
            fileLen = fis.available();
            if (fileLen > 10 * 1024 * 1024) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {

        }
        return b;
    }


    public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }


    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }

    /**
     * 版本号判断 是否低于后台版本
     */
    public static boolean getExtensionName(String code, String codeYse) {
        try {
            int intcode[] = StringToInt(code.split("\\."));
            int ints[] = StringToInt(codeYse.split("\\."));
            if (ints[0] > intcode[0]) {
                return true;
            } else if (ints[0] == intcode[0] && ints[1] > intcode[1]) {
                return true;
            } else if (ints[0] == intcode[0] && ints[1] == intcode[1] && ints[2] >= intcode[2]) {
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    public static int[] StringToInt(String[] arrs) {
        int[] ints = new int[arrs.length];
        for (int i = 0; i < arrs.length; i++) {
            Logger.i("ss" + arrs[i]);
            ints[i] = Integer.parseInt(arrs[i]);
        }
        return ints;
    }
}
